<html>
<head>

<title>Groovy Goodness: Are You In? (Membership Operator)</title>

<script language="javascript" src="scripts/shCore.js"></script> 
<script language="javascript" src="scripts/shLegacy.js"></script> 
<script language="javascript" src="scripts/shBrushJava.js"></script> 
<script language="javascript" src="scripts/shBrushXml.js"></script> 
<script language="javascript" src="scripts/shBrushJScript.js"></script> 
<script language="javascript" src="scripts/shBrushGroovy.js"></script> 
<script language="javascript" src="scripts/shBrushPlain.js"></script> 
<script language="javascript" src="scripts/shBrushBash.js"></script> 
 
<link href="styles/reset.css" rel="stylesheet" type="text/css" />
<link href="styles/shCore.css" rel="stylesheet" type="text/css" />
<link type="text/css" rel="stylesheet" href="styles/shThemeRDark.css"/>
<link href="styles/blog.css" rel="stylesheet" type="text/css" />

</head>
<body>

<a href="index.html">Back to index</a>

<h3 class="post-title">Groovy Goodness: Are You In? (Membership Operator)</h3>

<div class="post">
<p>Groovy brings some new operators and keywords to the table. One of them is the <em>in</em> keyword or the so-called membership operator. The operator can be called in a conditional context, for example we can use <em>in</em> to test for the existince of a member in a collection. We can write our own implementation by implementing the <code>isCase()</code> method of our class. Or the operator is called in an iterative context, for example in a for loop. Then the <code>iterator()</code> is called. We can write our own implementation for the <code>iterator()</code> to implement <em>in</em> when called in a iterative context.</p>
<pre class="brush:groovy">
// *** Conditional context
def list = ['Groovy', 'Java']
assert 'Groovy' in list
assert !('Scala' in list)

// Write our own in implementation.
class MyObject {
    String value
    boolean isCase(ch) { 
        value.contains(ch) 
    }
}
def myObj = new MyObject(value: 'Groovy')
assert 'oo' in myObj
assert !('oo' in myObj.value)  // isCase for String invokes equals.
assert 'Groovy' in myObj
assert 'Groovy' in myObj.value
assert !('a' in myObj)

// *** Iterative context
// Use in in a for loop.
def result = ''
for (lang in list ) {
    result += lang
}
assert 'GroovyJava' == result

class Counter {
    Integer maxValue
    private Integer counter = 0
    Iterator iterator() {
        [hasNext: { counter <= maxValue }, 
         next: { counter++ }] as Iterator
    }
}
def counter = new Counter(maxValue: 10)
result = '' 
for (c in counter) {
    result += c
}
assert result == '012345678910'
</pre
</div>

<script language="javascript"> 
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.clipboardSwf = 'scripts/clipboard.swf';
SyntaxHighlighter.defaults['first-line'] = 0;
SyntaxHighlighter.defaults['auto-links'] = false;
SyntaxHighlighter.all();
dp.SyntaxHighlighter.HighlightAll('code');
</script>

</body>
</html>